package com.ruoyi.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.workflow.domain.SysMessage;
import com.ruoyi.workflow.domain.vo.SysMessageVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.oa.domain.bo.OaMessageBo;
import com.ruoyi.oa.domain.vo.OaMessageVo;
import com.ruoyi.oa.domain.OaMessage;
import com.ruoyi.oa.mapper.OaMessageMapper;
import com.ruoyi.oa.service.IOaMessageService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 消息管理Service业务层处理
 *
 * @author ruoyi
 * @date 2023-07-31
 */
@RequiredArgsConstructor
@Service
public class OaMessageServiceImpl implements IOaMessageService {

    private final OaMessageMapper baseMapper;
    private final SysUserMapper sysUserMapper;

    /**
     * 查询消息管理
     */
    @Override
    public OaMessageVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询消息管理列表
     */
    @Override
    public TableDataInfo<OaMessageVo> queryPageList(OaMessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OaMessage> lqw = buildQueryWrapper(bo).orderByDesc(OaMessage::getCreateTime);
        Page<OaMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollectionUtil.isNotEmpty(result.getRecords())) {
            List<Long> userIds = result.getRecords().stream().map(OaMessageVo::getSendId).collect(Collectors.toList());
            List<Long> recordIds = result.getRecords().stream().map(OaMessageVo::getRecordId).collect(Collectors.toList());
            userIds.addAll(recordIds);
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(SysUser::getUserId, userIds);
            List<SysUser> sysUsers = sysUserMapper.selectList(wrapper);
            result.getRecords().forEach(e -> {
                SysUser recordUser = sysUsers.stream().filter(t -> t.getUserId().compareTo(e.getRecordId()) == 0).findFirst().orElse(null);
                SysUser sendUser = sysUsers.stream().filter(t -> t.getUserId().compareTo(e.getSendId()) == 0).findFirst().orElse(null);
                if (ObjectUtil.isNotEmpty(recordUser)) {
                    e.setRecordName(recordUser.getNickName());
                }
                if (ObjectUtil.isNotEmpty(sendUser)) {
                    e.setSendName(sendUser.getNickName());
                }
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询消息管理列表
     */
    @Override
    public List<OaMessageVo> queryList(OaMessageBo bo) {
        LambdaQueryWrapper<OaMessage> lqw = buildQueryWrapper(bo);
        List<OaMessageVo> oaMessageVos = baseMapper.selectVoList(lqw);
        if (CollectionUtil.isNotEmpty(oaMessageVos)) {
            List<Long> userIds = oaMessageVos.stream().map(OaMessageVo::getSendId).collect(Collectors.toList());
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(SysUser::getUserId, userIds);
            List<SysUser> sysUsers = sysUserMapper.selectList(wrapper);
            oaMessageVos.forEach(e -> {
                SysUser recordUser = sysUsers.stream().filter(t -> t.getUserId().compareTo(e.getRecordId()) == 0).findFirst().orElse(null);
                SysUser sendUser = sysUsers.stream().filter(t -> t.getUserId().compareTo(e.getSendId()) == 0).findFirst().orElse(null);
                if (ObjectUtil.isNotEmpty(recordUser)) {
                    e.setRecordName(recordUser.getNickName());
                }
                if (ObjectUtil.isNotEmpty(sendUser)) {
                    e.setSendName(sendUser.getNickName());
                }
            });
        }
        return oaMessageVos;
    }


    @Override
    public Integer scollList(){
        LambdaQueryWrapper<OaMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OaMessage::getStatus, false);
        wrapper.eq(OaMessage::getRecordId, LoginHelper.getUserId());
        List<OaMessage> list = baseMapper.selectList(wrapper);
        return list.size();
    }

    @Override
    public OaMessageVo getLastOne(Integer type){
        OaMessageBo bo = new OaMessageBo();
        bo.setType(type);
        LambdaQueryWrapper<OaMessage> lqw = buildQueryWrapper(bo).orderByDesc(OaMessage::getCreateTime);;
        List<OaMessageVo> oaMessageVos = baseMapper.selectVoList(lqw);
        if (CollectionUtil.isNotEmpty(oaMessageVos)){
            return oaMessageVos.get(0);
        }else {
            return null;
        }
    }

    private LambdaQueryWrapper<OaMessage> buildQueryWrapper(OaMessageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OaMessage> lqw = Wrappers.lambdaQuery();
        if (!LoginHelper.isAdmin()) {
            lqw.eq(OaMessage::getRecordId, LoginHelper.getUserId());
        }
        lqw.like(bo.getTitle() != null, OaMessage::getTitle, bo.getTitle());
        lqw.eq(bo.getSendId() != null, OaMessage::getSendId, bo.getSendId());
        lqw.eq(bo.getRecordId() != null, OaMessage::getRecordId, bo.getRecordId());
        lqw.eq(bo.getType() != null, OaMessage::getType, bo.getType());
        lqw.eq(bo.getStatus() != null, OaMessage::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getMessageContent()), OaMessage::getMessageContent, bo.getMessageContent());
        lqw.eq(bo.getReadTime() != null, OaMessage::getReadTime, bo.getReadTime());
        lqw.between(params.get("beginReadTime") != null && params.get("endReadTime") != null,
            OaMessage::getReadTime, params.get("beginReadTime"), params.get("endReadTime"));
        return lqw;
    }

    /**
     * 新增消息管理
     */
    @Override
    public Boolean insertByBo(OaMessageBo bo) {
        OaMessage add = BeanUtil.toBean(bo, OaMessage.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改消息管理
     */
    @Override
    public Boolean updateByBo(OaMessageBo bo) {
        OaMessage update = BeanUtil.toBean(bo, OaMessage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OaMessage entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除消息管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<OaMessageVo> queryPage() {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(1);
        pageQuery.setPageSize(3);
        LambdaQueryWrapper<OaMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OaMessage::getStatus, 0);
        wrapper.eq(OaMessage::getRecordId, LoginHelper.getUserId());
        Page<OaMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public boolean readMessage(Long id) {
        OaMessage oaMessage = baseMapper.selectById(id);
        oaMessage.setStatus(1);
        oaMessage.setReadTime(new Date());
        return baseMapper.updateById(oaMessage) > 0;
    }

    @Override
    public boolean batchReadMessage(String type) {
        LambdaQueryWrapper<OaMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OaMessage::getRecordId, LoginHelper.getUserId());
        wrapper.eq(OaMessage::getType,type);
        List<OaMessage> messageList = baseMapper.selectList(wrapper);
        messageList.forEach(oaMessage -> {
            oaMessage.setStatus(1);
            oaMessage.setReadTime(new Date());
        });
        if (messageList.size() > 0) {
            return baseMapper.updateBatchById(messageList);
        } else {
            return true;
        }
    }

    @Override
    public Boolean sendBatchMessage(List<OaMessage> messageList) {
        return baseMapper.insertBatch(messageList);
    }

    @Override
    public List<Map<String, Object>> getAllHasAuth(String deptId,String nickName) {
        return baseMapper.getAllHasAuth(deptId,nickName);
    }


    @Override
    public List<Map<String, Object>> getAllNotAuth(String deptId,String nickName) {
        return baseMapper.getAllNotAuth(deptId,nickName);
    }
}
